import { BaseService, CoolCommException } from "@cool-midway/core";
import { Inject, Provide } from "@midwayjs/core";
import { Equal, Repository, In } from "typeorm";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { CarInfoEntity } from "../../entity/car/info";
import { AddCarDTO } from "../../dto/car";
import { CapacityEntity } from "../../entity/capacity";
import { TransportType } from "../../entity/type";
import { ProviderTeamEntity } from "../../../provider/entity/team";
import { ProviderProfileEntity } from "../../../provider/entity/profile";
import { Context } from "@midwayjs/koa";

@Provide()
export class CarInfoService extends BaseService {
    @InjectEntityModel(CarInfoEntity)
    carInfoModel: Repository<CarInfoEntity>

    @InjectEntityModel(CapacityEntity)
    capacityModel: Repository<CapacityEntity>

    @InjectEntityModel(ProviderTeamEntity)
    teamModel: Repository<ProviderTeamEntity>

    @InjectEntityModel(ProviderProfileEntity)
    profileModel: Repository<ProviderProfileEntity>

    @Inject()
    ctx: Context

    /**
     * 获取服务人员绑定的车辆信息
     * @param providerId 服务人员ID
     * @returns 车辆信息
     */
    async getByProviderId(providerId: number) {
        return this.carInfoModel.find({ where: { providerId: Equal(providerId) } });
    }

    /**
     * 获取团队绑定的车辆信息
     * @param teamId 团队ID
     * @returns 车辆信息
     */
    async getByTeamId(teamId: number) {
        return this.carInfoModel.find({ where: { teamId: Equal(teamId) } });
    }

    /**
     * 获取当前用户所属团队下的车辆列表
     */
    async listByCurrentTeam() {
        const providerId = this.ctx.provider?.id;
        if (!providerId) {
            throw new CoolCommException('未登录或缺少服务人员信息');
        }
        // 计算 teamId：优先拥有的团队，否则取加入的团队（通过个人运力）
        let teamId: number | null = null;
        const ownerTeam = await this.teamModel.findOne({ where: { ownerProviderId: Equal(providerId) } });
        if (ownerTeam) {
            teamId = ownerTeam.id;
        } else {
            const profile = await this.profileModel.findOne({ where: { providerId: Equal(providerId) } });
            if (!profile) {
                throw new CoolCommException('请先完善个人资料');
            }
            const myCapacity = await this.capacityModel.findOne({ where: { id: Equal(profile.capacityId) } });
            teamId = myCapacity?.teamId ?? null;
        }
        if (!teamId) {
            throw new CoolCommException('请先加入或创建团队');
        }
        return this.getByTeamId(teamId);
    }

    /**
     * 返回当前用户视角的车辆列表（数组）：
     * - 若为团队所有者：该团队所有车辆 + 我的车辆（去重）
     * - 若无上级所属（无 teamId）：仅我的车辆
     * - 否则：所属团队车辆 + 我的车辆（去重）
     */
    async listForCurrentUser() {
        const providerId = this.ctx.provider?.id;
        if (!providerId) {
            throw new CoolCommException('未登录或缺少服务人员信息');
        }
        const myCar = await this.getByProviderId(providerId); // 数组

        // 是否团队所有者
        const ownerTeam = await this.teamModel.findOne({ where: { ownerProviderId: Equal(providerId) } });
        if (ownerTeam) {
            const teamCars = await this.getByTeamId(ownerTeam.id);
            const merged = [...teamCars, ...myCar];
            const seen = new Set<number>();
            return merged.filter(c => {
                if (!c) return false;
                if (seen.has(c.id)) return false;
                seen.add(c.id);
                return true;
            });
        }

        // 非团队所有者：查是否有上级所属（通过 capacity.teamId 判断）
        const profile = await this.profileModel.findOne({ where: { providerId: Equal(providerId) } });
        if (!profile) {
            // 无资料，仅返回个人车辆
            return [...myCar];
        }
        const myCapacity = await this.capacityModel.findOne({ where: { id: Equal(profile.capacityId) } });
        const teamId = myCapacity?.teamId ?? null;
        if (!teamId) {
            // 无所属团队，仅返回个人车辆
            return [...myCar];
        }
        const teamCars = await this.getByTeamId(teamId);
        const merged = [...teamCars, ...myCar];
        const seen = new Set<number>();
        return merged.filter(c => {
            if (!c) return false;
            if (seen.has(c.id)) return false;
            seen.add(c.id);
            return true;
        });
    }

    /**
     * 服务人员新增车辆：创建车辆、生成运力并绑定当前人员与团队
     */
    async addMyCar(dto: AddCarDTO) {
        const providerId = this.ctx.provider?.id;
        if (!providerId) {
            throw new CoolCommException('未登录或缺少服务人员信息');
        }

        // 计算 teamId：优先拥有的团队，否则取加入的团队（通过个人运力）
        let teamId: number | null = null;
        const ownerTeam = await this.teamModel.findOne({ where: { ownerProviderId: Equal(providerId) } });
        if (ownerTeam) {
            teamId = ownerTeam.id;
        } else {
            const profile = await this.profileModel.findOne({ where: { providerId: Equal(providerId) } });
            if (!profile) {
                throw new CoolCommException('请先完善个人资料');
            }
            const myCapacity = await this.capacityModel.findOne({ where: { id: Equal(profile.capacityId) } });
            teamId = myCapacity?.teamId ?? null;
        }
        if (!teamId) {
            throw new CoolCommException('请先加入或创建团队');
        }

        // 事务：创建运力并保存车辆
        return await this.carInfoModel.manager.transaction(async manager => {
            const capacity = await manager.save(CapacityEntity, {
                type: TransportType.CAR,
                teamId,
            });

            const car = await manager.save(CarInfoEntity, {
                providerId,
                teamId,
                capacityId: capacity.id,
                licensePlate: dto.licensePlate,
                model: dto.model,
                typeId: dto.typeId,
                brand: dto.brand,
                photo: dto.photo,
                remark: dto.remark,
                tags: dto.tags,
                color: dto.color,
            });

            return car;
        });
    }

    async delete(ids: any): Promise<void> {
        const providerId = this.ctx.provider?.id;
        if (!providerId) {
            throw new CoolCommException('未登录或缺少服务人员信息');
        }
        const idList: number[] = Array.isArray(ids) ? ids : [ids];
        if (idList.length === 0) return;

        // 查询待删除车辆
        const cars = await this.carInfoModel.find({ where: { id: In(idList) } });
        if (!cars.length) {
            throw new CoolCommException('车辆不存在');
        }

        // 判断是否团队所有者
        const ownerTeam = await this.teamModel.findOne({ where: { ownerProviderId: Equal(providerId) } });

        // 计算有权限删除的车辆
        const permittedCars = ownerTeam
            ? cars.filter(c => c.teamId === ownerTeam.id)
            : cars.filter(c => c.providerId === providerId);

        if (permittedCars.length !== cars.length) {
            throw new CoolCommException('存在无权限删除的车辆');
        }

        // 删除车辆与对应运力（事务）
        await this.carInfoModel.manager.transaction(async manager => {
            const capacityIds = permittedCars.map(c => c.capacityId).filter(Boolean);
            if (capacityIds.length) {
                await manager.delete(CapacityEntity, { id: In(capacityIds as number[]) });
            }
            await manager.delete(CarInfoEntity, { id: In(permittedCars.map(c => c.id)) });
        });
    }
}